package com.example.qimowork.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.qimowork.R;
import com.example.qimowork.ShuJu.Data;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.util.List;

public class ShouYeAdapter extends BaseAdapter {
    private Context context;
    private List<Data> dataList;

    public ShouYeAdapter(Context context, List<Data> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        return dataList !=null ? dataList.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        return dataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        LayoutInflater inflater = LayoutInflater.from(context);
        if (convertView==null){
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item,null);
            holder.iv = convertView.findViewById(R.id.item_iv);
            holder.tv = convertView.findViewById(R.id.item_tv);

            Bitmap bitmap= setPosterBitmap(dataList.get(position).getThumbnail_pic_s());
            holder.iv.setImageBitmap(bitmap);

            holder.tv.setText(dataList.get(position).getTitle());
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder)convertView.getTag();
        }
        return convertView;
    }

    public class ViewHolder{
        private ImageView iv;
        private TextView tv;
    }

    Bitmap setPosterBitmap(String url) {
        final Bitmap[] mBitmap = new Bitmap[1];
        Picasso.get().load(url).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                mBitmap[0] = bitmap;
            }

            @Override
            public void onBitmapFailed(Exception e, Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        });
        return mBitmap[0];
    }
}
